package com.tianlu.store.controller;

import cn.hutool.core.util.StrUtil;
import com.tianlu.store.common.*;
import com.tianlu.store.dto.ScoreDetailDTO;
import com.tianlu.store.dto.TeamPerformanceDTO;
import com.tianlu.store.dto.UpdatePasswordDTO;
import com.tianlu.store.entity.ScoreDetail;
import com.tianlu.store.entity.UserInfo;
import com.tianlu.store.service.UserInfoService;
import com.tianlu.store.utils.JwtUtils;
import com.tianlu.store.utils.RedisTemplateUtils;
import com.tianlu.store.utils.WxUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author 梁东烂
 * @Desc 用户表(UserInfo)表控制层
 * @Date 2023-04-01 17:28:49
 */
@Api(tags = "用户表")
@RestController
@RequestMapping("/api/userInfo")
@RequiredArgsConstructor
public class UserInfoController {
	@Resource
    private UserInfoService userInfoService;
	
	@ApiOperation("用户表列表(分页）接口")
    @PostMapping("/findPage")
    public ResponseResult<PageResult<UserInfo>> findPage(@RequestBody UserInfo userInfo) {
        return ResponseResult.success(userInfoService.findPage(userInfo));
    }
	
	@ApiOperation("用户表列表(不分页）接口")
    @PostMapping("/findList")
    public ResponseResult<List<UserInfo>> findList(@RequestBody UserInfo userInfo) {
        return ResponseResult.success(userInfoService.findList(userInfo));
    }
	
	@ApiOperation("查看用户表接口")
    @GetMapping(value = "/detail")
    public ResponseResult<UserInfo> detail() {
        Long id = JwtUtils.getIdByJwtToken();
        return ResponseResult.success(userInfoService.getById(id));
    }

	@ApiOperation("添加用户表接口")
    @PostMapping("/save")
    public ResponseResult<Boolean> save(@RequestBody @Valid UserInfo userInfo) {
        userInfo.setId(IdGen.snowflakeId());
        return ResponseResult.success(userInfoService.save(userInfo));
    }
	
	@ApiOperation("修改用户表接口")
    @PostMapping("/update")
    public ResponseResult<Boolean> update(@RequestBody UserInfo userInfo) {
        if (Objects.isNull(userInfo.getId())) {
            return ResponseResult.fail(ResultCode.CODE_400, "ID不能为空");
        }
        return ResponseResult.success(userInfoService.updateById(userInfo));
    }
	
	@ApiOperation("删除用户表接口")
    @PostMapping("/deleteByIds")
    public ResponseResult<Boolean> deleteByIds(@RequestParam List<Long> ids) {
        return ResponseResult.success(userInfoService.removeByIds(ids));
    }

    @ApiOperation("查询团队成员接口")
    @PostMapping("/findGroupTree")
    public ResponseResult<List<UserInfo>> findGroupTree(@RequestParam Long id) {
        return ResponseResult.success(userInfoService.findGroupTree(id));
    }

    @ApiOperation("查询当前用户积分明细接口")
    @PostMapping("/findScoreDetail")
    public ResponseResult<List<ScoreDetailDTO>> findScoreDetail(@RequestParam Long userId) {
        return ResponseResult.success(userInfoService.findScoreDetail(userId));
    }

    @ApiOperation("查询当前用户团队业绩接口")
    @PostMapping("/findPerformanceDetail")
    public ResponseResult<List<TeamPerformanceDTO>> findPerformanceDetail(@RequestParam Long userId) {
        return ResponseResult.success(userInfoService.findPerformanceDetail(userId));
    }

    @ApiOperation("查询当前用户团队成员接口")
    @PostMapping("/findTeamMembers")
    public ResponseResult<List<UserInfo>> findTeamMembers(@RequestParam Long id) {
        return ResponseResult.success(userInfoService.findTeamMembers(id));
    }

    @ApiOperation("后台系统登录接口")
    @PostMapping("/backLogin")
    @NoCheckToken
    public ResponseResult<String> backLogin(@RequestParam String userName, @RequestParam String password) {
        UserInfo userInfo = userInfoService.getByPhone(userName);
        if (Objects.isNull(userInfo)) {
            return ResponseResult.fail(ResultCode.CODE_400, "账号错误！");
        }

        if (password.equals(userInfo.getPassword())) {
            String jwtToken = JwtUtils.getJwtToken(userInfo.getId(), userInfo.getOpenId(), userInfo.getName(), userInfo.getPhone(), userInfo.getStatus(), userInfo.getLevel());
            RedisTemplateUtils.set(Constant.USER_TOKEN_PREFIX + jwtToken, jwtToken, Constant.USER_LOGIN_TOKEN_TIME);
            return ResponseResult.success(jwtToken);
        }
        return ResponseResult.fail(ResultCode.CODE_400, "密码错误！");
    }

    @ApiOperation("登出接口")
    @PostMapping("/logout")
    public ResponseResult<Boolean> logout(HttpServletRequest request) {
        String token = request.getHeader(Constant.HEADER_TOKEN);
        if(StrUtil.isEmpty(token)){
            return ResponseResult.fail(ResultCode.CODE_402);
        }
        RedisTemplateUtils.del(Constant.USER_TOKEN_PREFIX + token);
        return ResponseResult.success(true);
    }

    @ApiOperation("小程序登录接口")
    @PostMapping("/wxLogin")
    @NoCheckToken
    public ResponseResult<UserInfo> wxLogin(@RequestParam String code) {
        return ResponseResult.success(userInfoService.wxLogin(code));
    }

    @ApiOperation("获取手机号码")
    @PostMapping("/getPhoneNumber")
    @NoCheckToken
    public ResponseResult<String> getPhoneNumber(@RequestParam String code) {
        return ResponseResult.success(userInfoService.getPhoneNumber(code));
    }

    @ApiOperation("注册")
    @PostMapping("/signUp")
    @NoCheckToken
    public ResponseResult<UserInfo> signUp(@RequestBody @Valid UserInfo userInfo) {
        userInfo.setId(IdGen.snowflakeId());
        return ResponseResult.success(userInfoService.signUp(userInfo));
    }

    @ApiOperation("根据电话查询人员信息")
    @PostMapping("/getByPhone")
    @NoCheckToken
    public ResponseResult<UserInfo> getByPhone(@RequestParam String phoneNumber) {
        return ResponseResult.success(userInfoService.getByPhone(phoneNumber));
    }

    @ApiOperation("根据电话查询人员信息")
    @PostMapping("/getByCode")
    @NoCheckToken
    public ResponseResult<UserInfo> getByCode(@RequestParam String code) {
        return ResponseResult.success(userInfoService.getByCode(code));
    }

    @ApiOperation("赠送积分")
    @PostMapping("/giveScore")
    public ResponseResult<Boolean> giveScore(@RequestParam Long receiveId, BigDecimal score) {
        Long userId = JwtUtils.getIdByJwtToken();
        userInfoService.giveScore(userId, receiveId, score);
        return ResponseResult.success(true);
    }

    @ApiOperation("修改密码")
    @PostMapping("/updatePassword")
    public ResponseResult<Boolean> updatePassword(@RequestBody @Valid UpdatePasswordDTO updatePasswordDTO) {
        return ResponseResult.success(userInfoService.updatePassword(updatePasswordDTO));
    }
}
